// 处理路由权限
import { privateRoutes, publicRoutes } from '@/router'

export default {
  namespaced: true,
  state: () => ({
    // 初始静态路由
    routes: publicRoutes
  }),
  mutations: {
    // 增加路由
    setRoutes (state, newRoutes) {
      // 永远在静态路由的基础上增加新路由
      state.routes = [...publicRoutes, ...newRoutes]
    }
  },
  actions: {
    // 根据权限筛选路由
    filterRoutes ({ state, commit }, menus) {
      const routes = []
      // 路由权限匹配
      menus.forEach(key => {
        // 匹配出路由
        routes.push(...privateRoutes.filter(item => item.name === key))
      })

      // 最后添加404页面
      routes.push({
        path: '/:catchAll(.*)',
        redirect: '/404'
      })
      commit('setRoutes', routes)
      return routes
    }
  }
}
